<template>
  <div class="upload-container">
    <el-upload
      class="upload-demo"
      drag
      action="/api/upload"  # 替换为实际后端接口
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
      :show-file-list="false"
      accept=".jpg,.jpeg,.png,.pdf,.txt"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        拖拽试卷文件到此处或<em>点击上传</em>
      </div>
    </el-upload>
    
    <el-input
      v-if="showTextInput"
      v-model="textContent"
      type="textarea"
      :rows="10"
      placeholder="或者直接在此输入试卷内容..."
      class="text-input"
    />
    
    <el-button 
      type="primary" 
      @click="submitForGrading"
      :loading="isLoading"
    >
      提交批改
    </el-button>
    
    <el-switch
      v-model="showTextInput"
      active-text="输入文本"
      inactive-text="上传文件"
      class="switch-input"
    />
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useStore } from '../stores/auth';
import { gradePaper } from '../api/zhipuai';
import { ElMessage } from 'element-plus';

const store = useStore();
const showTextInput = ref(false);
const textContent = ref('');
const isLoading = ref(false);
const emit = defineEmits(['grading-complete']);

const beforeUpload = (file) => {
  const isImage = ['image/jpeg', 'image/png'].includes(file.type);
  const isText = ['text/plain', 'application/pdf'].includes(file.type);
  const isLt5M = file.size / 1024 / 1024 < 5;
  
  if (!isImage && !isText) {
    ElMessage.error('只能上传图片或文本文件!');
    return false;
  }
  if (!isLt5M) {
    ElMessage.error('文件大小不能超过5MB!');
    return false;
  }
  return true;
};

const handleSuccess = (response) => {
  if (response.success) {
    ElMessage.success('上传成功');
    // 如果是图片，保存URL
    if (response.data.imageUrl) {
      submitForGrading(response.data.imageUrl);
    }
  } else {
    ElMessage.error(response.message);
  }
};

const submitForGrading = async (imageUrl = null) => {
  if (!textContent.value && !imageUrl) {
    ElMessage.warning('请上传试卷或输入内容');
    return;
  }
  
  isLoading.value = true;
  try {
    const result = await gradePaper(textContent.value, imageUrl);
    emit('grading-complete', result);
  } catch (error) {
    ElMessage.error('批改过程中出错: ' + error.message);
  } finally {
    isLoading.value = false;
  }
};
</script>

<style scoped>
.upload-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.text-input {
  margin-top: 20px;
}

.switch-input {
  align-self: flex-end;
}
</style>